#include "com_dialog_test.h"
#include "ui_com_dialog_test.h"
#include "pub_var.h"
#include "QPushButton"
#include <QDebug>
#include <QDate>
#include <QMessageBox>
#include <QRegExp>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QTimer>
#include <QFile>
#include <QFileDialog>
#include <QRandomGenerator>
#include <QSqlRecord>


#include <QByteArray>
#include <QtCore>
#include <algorithm>


//select * from met_ord_recipedetail where doct_code = '010050' and oper_date > to_date('2022-1-1', 'yyyy-mm-dd')

Dialog_datatrans::Dialog_datatrans(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog_datatrans)
{
    ui->setupUi(this);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);
    qro0 = new QSqlQuery(pub::db_o);
    qrm = new QSqlQuery(pub::db_m);
    qrmt = new QSqlQuery(pub::db_m);
    qrm_new = new QSqlQuery(pub::db_m);
    qrm_old = new QSqlQuery(pub::db_m);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/trans").toRect();
    this->setGeometry(rct);

    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    pop_3103 = new Ys_bzgl_3103();
    jxc = new Form_qlsjsc();

}

Dialog_datatrans::~Dialog_datatrans()
{
    delete ui;
}

void Dialog_datatrans::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event)

    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/trans", QVariant(this->geometry()));
    void destroyW();
}


void Dialog_datatrans::on_pbRun_clicked()
{
    ui->teOut->clear();
    QJsonObject inpu;
    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(ui->teIn->toPlainText().toUtf8().data(), &json_error);
    if(json_error.error != 0 )
    {
        ui->teOut->insertPlainText( "入参Json解析错误 " + json_error.errorString());
        return ;
    }

    inpu = jsdc.object();

    QString info;
    QJsonObject retValue;

    if(ui->ckbSaveFile->isChecked())
    {
        if(ui->leConstrain->text().isEmpty())
        {
            ui->teOut->insertPlainText( "未指定导出文件名称！");
            return;
        }
        if( ! pub::call_business(ui->leCode->text(), inpu, info, retValue, ui->leConstrain->text(), true , manager, request))
            //if( ! pub::call_business(ui->leCode->text(), inpu, info, retValue, "0000.txt", true , manager, request))
        {
            ui->teOut->insertPlainText( info);
        }
        return;
    }
    else
    {
        if( ! pub::call_business(ui->leCode->text(), inpu, info, retValue, "", true , manager, request))
        {
            ui->teOut->insertPlainText( info);
            return ;
        }
    }


    if(retValue.size() == 0)
    {
        ui->teOut->insertPlainText( "交易返回信息为空。");
    }
    else
    {
        jsdc = QJsonDocument(retValue);
        ui->teOut->insertPlainText( jsdc.toJson(QJsonDocument::Compact));
    }
}

void Dialog_datatrans::on_pbExit_clicked()
{
    close();
}

void Dialog_datatrans::on_toolButton_clicked()
{
    QFileDialog *fileDialog = new QFileDialog(this);

    QString str = fileDialog->getOpenFileName();
    if(str.isEmpty())
    {
        return;
    }
    else
    {
        ui->leConstrain->setText(str);
    }
}

void Dialog_datatrans::on_pushButton_clicked()
{
    if(ui->comboBox->duplicatesEnabled() == true)
    {
        ui->comboBox->setDuplicatesEnabled(false);
    }else{
        ui->comboBox->setDuplicatesEnabled(true);
    }

}

void Dialog_datatrans::on_pushButton_2_clicked()
{
    ui->comboBox->addItem("this is a test item");
}


/*
    sq = "select clinic_code , medical_plan from ys_bz_e_rec "//where clinic_code = '6011928'"; // and sm3 is null
         " where rq >= '2023-1-1' and sm3 is null"; //
    qrmt->exec(sq);
    int count = 0;
    while(qrmt->next())
    {
        QString cod = qrmt->value(0).toString();
        QString pln = qrmt->value(1).toString();
        QString sm3 = calc_sm3(cod, pln);

        sq = "update ys_bz_e_rec set sm3 = '"+sm3+"' where clinic_code = '" + cod+ " '";
        qrm->exec(sq);

        sq = "insert into ys_bz_e_rec_sm3 (tmstmp, tmstmp_count, sm3_code, clinic_code)"
             " values(now(), %1, '%2', '%3')" ;
        sq = sq.arg("0").arg(sm3).arg(cod);
        qDebug()<<"save ys_bz_e_rec_sm3 : "<<sq<<"\n";

        qrm->exec(sq);

        chang(cod);

        ui->leConstrain->setText(QString::number(count++) + " , " + cod);
        qApp->processEvents();

    }

*/

QString Dialog_datatrans::calc_sm3(QString clinic_code,QString plan)
{
    QString calc = "";
    //从数据库提取基础病志内容
    sq = " select * from ys_bz_e_rec where clinic_code = '%1' ";
    sq = sq.arg(clinic_code);
    qDebug()<<"变更诊疗计划，从数据库提取基础病志内容"<<sq<<" \n";
    qrm->exec(sq);
    if(!qrm->next())
    {
        qDebug()<<"未找到基础病志内容 \n";
        return "";
    }

    calc += qrm->value("jzyy").toString();
    calc += qrm->value("hzzs").toString();
    calc += qrm->value("xbs").toString();
    calc += qrm->value("jws").toString();
    calc += qrm->value("gms").toString();
    calc += qrm->value("person_hist").toString();
    calc += qrm->value("menstr_hist").toString();
    calc += qrm->value("family_hist").toString();
    calc += qrm->value("tgjc").toString();
    calc += qrm->value("yz").toString();

    //西医诊断
    calc += qrm->value("zd1").toString();

    if(!qrm->value("zd2").toString().isEmpty())
    {
        calc += "^" + qrm->value("zd2").toString();
    }

    if(!qrm->value("zd3").toString().isEmpty())
    {
        calc += "^" + qrm->value("zd3").toString();
    }

    //中医诊断
    calc += qrm->value("zyzd1").toString() + "/" + qrm->value("zyzh1").toString();

    if(qrm->value("zyzd2").toString() + "/" + qrm->value("zyzh2").toString() != "/")
    {
        calc += "^" + qrm->value("zyzd2").toString() + "/" + qrm->value("zyzh2").toString();
    }

    if(qrm->value("zyzd3").toString() + "/" + qrm->value("zyzh3").toString() != "/")
    {
        calc += "^" + qrm->value("zyzd3").toString() + "/" + qrm->value("zyzh3").toString();
    }

    calc += qrm->value("tgjc_tr").toString();
    calc += qrm->value("zybz").toString();
    calc += qrm->value("similar_syndrom").toString();
    calc += qrm->value("treat_tr").toString();

    calc += plan;



    //计算 sm3 code
    QString calc_sm3 = pub::gmssl_sm3(pub::hos_ybbh + calc + qrm->value("doct_code").toString()).trimmed();

    return calc_sm3;

}

void Dialog_datatrans::chang(QString clinic_code)
{

    int change_status = 0;

    //qrm_new->exec("select * from ys_bz_e_rec where clinic_code = '"+clinic_code+"'");
    qrm_old->exec("select * from ys_bz_e_rec_bk where clinic_code = '"+clinic_code+"' order by tmstmp");
    qrm_new->exec("select * from ys_bz_e_rec_bk where clinic_code = '"+clinic_code+"' order by tmstmp");


    if(!qrm_new->next())
    {
        qDebug()<<clinic_code<<" has no data in ys_bz_e_rec_bk.\n";
        return;
    }

    qDebug()<<"new atinc : "<<qrm_new->value("atinc").toString()<<"\n";

    while(true)
    {
        bool need_exit = false;
        qrm_old->next();
        qDebug()<<"old atinc : "<<qrm_old->value("atinc").toString()<<"\n";

        QDateTime d = qrm_old->value("tmstmp").toDateTime();

        QString tmstmp = QString::number(d.toMSecsSinceEpoch());

        if(!qrm_new->next())
        {
            need_exit = true;
            qrm_new->exec("select * from ys_bz_e_rec where clinic_code = '"+clinic_code+"'");
            qrm_new->next();
            qDebug()<<"normal new atinc : "<<qrm_new->value("atinc").toString()<<"\n";
        }
        else
        {
        qDebug()<<"new atinc : "<<qrm_new->value("atinc").toString()<<"\n";
        }



        change_status += save_rec_hist("就诊原因", qrm_new->value("jzyy").toString(),
                                       qrm_old->value("jzyy").toString(),
                                       tmstmp, clinic_code);

        change_status += save_rec_hist("患者主诉", qrm_new->value("hzzs").toString(),
                                       qrm_old->value("hzzs").toString(),
                                       tmstmp, clinic_code);

        change_status += save_rec_hist("现病史", qrm_new->value("xbs").toString(),
                                       qrm_old->value("xbs").toString(),
                                       tmstmp, clinic_code);

        change_status += save_rec_hist("既往史", qrm_new->value("jws").toString(),
                                       qrm_old->value("jws").toString(),
                                       tmstmp, clinic_code);

        change_status += save_rec_hist("过敏史", qrm_new->value("gms").toString(),
                                       qrm_old->value("gms").toString(),
                                       tmstmp, clinic_code);

        change_status += save_rec_hist("个人史", qrm_new->value("person_hist").toString(),
                                       qrm_old->value("person_hist").toString(),
                                       tmstmp, clinic_code);

        change_status += save_rec_hist("月经史", qrm_new->value("menstr_hist").toString(),
                                       qrm_old->value("menstr_hist").toString(),
                                       tmstmp, clinic_code);

        change_status += save_rec_hist("家族史", qrm_new->value("family_hist").toString(),
                                       qrm_old->value("family_hist").toString(),
                                       tmstmp, clinic_code);

        change_status += save_rec_hist("体格检查", qrm_new->value("tgjc").toString(),
                                       qrm_old->value("tgjc").toString(),
                                       tmstmp, clinic_code);

        change_status += save_rec_hist("医嘱", qrm_new->value("yz").toString(),
                                       qrm_old->value("yz").toString(),
                                       tmstmp, clinic_code);



        //西医诊断
        QString diag_new = qrm_new->value("zd1").toString();

        if(!qrm_new->value("zd2").toString().isEmpty())
        {
            diag_new += "^" + qrm_new->value("zd2").toString();
        }

        if(!qrm_new->value("zd3").toString().isEmpty())
        {
            diag_new += "^" + qrm_new->value("zd3").toString();
        }

        QString diag_old = qrm_old->value("zd1").toString();

        if(!qrm_old->value("zd2").toString().isEmpty())
        {
            diag_old += "^" + qrm_old->value("zd2").toString();
        }

        if(!qrm_old->value("zd3").toString().isEmpty())
        {
            diag_old += "^" + qrm_old->value("zd3").toString();
        }

        change_status +=  save_rec_hist("西医诊断", diag_new, diag_old, tmstmp, clinic_code);




        //中医诊断
        diag_new = qrm_new->value("zyzd1").toString() + "/" + qrm_new->value("zyzh1").toString();

        if(qrm_new->value("zyzd2").toString() + "/" + qrm_new->value("zyzh2").toString() != "/")
        {
            diag_new += "^" + qrm_new->value("zyzd1").toString() + "/" + qrm_new->value("zyzh1").toString();
        }

        if(qrm_new->value("zyzd3").toString() + "/" + qrm_new->value("zyzh3").toString() != "/")
        {
            diag_new += "^" + qrm_new->value("zyzd3").toString() + "/" + qrm_new->value("zyzh3").toString();
        }

        diag_old = qrm_old->value("zyzd1").toString() + "/" + qrm_old->value("zyzh1").toString();

        if(qrm_old->value("zyzd2").toString() + "/" + qrm_old->value("zyzh2").toString() != "/")
        {
            diag_old += "^" + qrm_old->value("zyzd2").toString() + "/" + qrm_old->value("zyzh2").toString();
        }

        if(qrm_old->value("zyzd3").toString() + "/" + qrm_old->value("zyzh3").toString() != "/")
        {
            diag_old += "^" + qrm_old->value("zyzd3").toString() + "/" + qrm_old->value("zyzh3").toString();
        }

        change_status +=  save_rec_hist("中医诊断", diag_new, diag_old, tmstmp, clinic_code);


        change_status += save_rec_hist("中医查体", qrm_new->value("tgjc_tr").toString(),
                                       qrm_old->value("tgjc_tr").toString(),
                                       tmstmp, clinic_code);

        change_status += save_rec_hist("中医辩证依据", qrm_new->value("zybz").toString(),
                                       qrm_old->value("zybz").toString(),
                                       tmstmp, clinic_code);

        change_status += save_rec_hist("中医类证鉴别", qrm_new->value("similar_syndrom").toString(),
                                       qrm_old->value("similar_syndrom").toString(),
                                       tmstmp, clinic_code);

        change_status += save_rec_hist("中医治则", qrm_new->value("treat_tr").toString(),
                                       qrm_old->value("treat_tr").toString(),
                                       tmstmp, clinic_code);

        if(need_exit)
        {
            break;
        }
    }


    //if(change_status > 0)
    //{
    //    //关键内容发生变化，保存 sm3
    //    sq = "insert into ys_bz_e_rec_sm3 (tmstmp, tmstmp_count, sm3_code, clinic_code)"
    //         " values(now(), %1, '%2', '%3')" ;
    //    sq = sq.arg(tmstmp).arg("calc_sm3").arg(clinic_code);
    //    qDebug()<<"save ys_bz_e_rec_sm3 : "<<sq<<"\n";

    //    if(!qrm->exec(sq))
    //    {
    //        QMessageBox::information(this, "注意", "保存 sm3 校验码失败！ ");
    //        qDebug()<<"保存 sm3 校验码失败！\n";
    //        return ;
    //    }
    //}
}


int Dialog_datatrans::save_rec_hist(QString fld_name, //字段名
                                    QString fld_new, //新值
                                    QString fld_old, //旧值
                                    QString tmstmp, //时间戳
                                    QString clinic_code)//
{

    if(fld_new == fld_old)
    {
        return 0;   //未变化
    }

    QString str_sql;
    str_sql = "insert into ys_bz_e_rec_hist"
              "(clinic_code,oper_time,tmstmp_count,fld_name,fld_new,fld_old)"
              "values("
              "'%1',"
              "now(),"//oper_time
            "%2,"//tmstmp_count
            "'%3',"//fld_name
            "'%4',"//fld_new
            "'%5'"//fld_old
            ")";
    str_sql = str_sql.arg(clinic_code)
            .arg(tmstmp)
            .arg(fld_name)
            .arg(fld_new)
            .arg(fld_old);
    qDebug()<<"保存历史记录："<<str_sql<<"\n";

    if(qrm->exec(str_sql))
    {
        return 1;   //保存成功
    }
    else
    {
        return -1;  //保存失败
    }

}


void Dialog_datatrans::on_pbShowFields_clicked()
{

    pub::db_o.transaction();

    sq = "update fin_opb_invoicedetail set invo_sequence  = '3' where INVOICE_NO = '000000742163'";
    qro->exec("select invo_sequence from fin_opb_invoicedetail  where INVOICE_NO = '000000742163'");
    pub::db_o.rollback();

    ui->teOut->insertPlainText( "All done. ");


    /*
        //设置作废标记
        sq = " update fin_ipr_siinmaininfo set valid_flag = '0' "
             " where invoice_no = '" + mpPerson["invoice_no"] + "'";
        qDebug()<<"设置作废标记:"<<sq<<"\n";
        qro->exec(sq);

    */


}

